<?php

namespace App\Job\Console\Commands\Order;

use App\Models\ItemOrder;
use App\Models\OrderCommission;
use App\Repositories\User\PublisherRepositoryInterface;
use App\Repositories\User\UserRepositoryInterface;
use Illuminate\Console\Command;

class OrderCommissionInit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:commission:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单佣金分成初始化：统计订单中分成方获取佣金金额';

    /**
     * @var UserRepositoryInterface
     */
    private $user_repository;

    /**
     * @var PublisherRepositoryInterface
     */
    private $publisher_repository;

    public function __construct()
    {
        parent::__construct();

        $this->user_repository = app(UserRepositoryInterface::class);
        $this->publisher_repository = app(PublisherRepositoryInterface::class);
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('====开始时间：' . date('Y-m-d H:i:s'));
        ItemOrder::query()
            ->where('status', ItemOrder::PAID_SUCCESS)
            ->where('is_commission_init', 0)
            ->where('is_commission_strike', 0)
            ->chunkById(10, function ($orders) {
                foreach ($orders as $order) {
                    $this->info('订单信息');
                    $this->info(print_r($order->toArray(), true));
                    //是否已佣金初始化
                    if (!$this->isOrderCommissionInit($order)) {
                        //用户邀请分成计算
                        $this->userInviteCommissionInit($order);
                        //发布者邀请分成计算
                        $this->publisherInviteCommissionInit($order);
                    }

                    //完成初始化标识
                    $this->completeCommissionInit($order->id);
                }
            });

        $this->info('==结束==');
    }

    /**
     * 买家邀请佣金提成
     *
     * @param ItemOrder $order
     */
    private function userInviteCommissionInit(ItemOrder $order)
    {
        $user_id = $order->user_id;
        $invite_uid = $this->user_repository->getUserInviteUid($user_id);
        if (!$invite_uid) {
            return;
        }

        //邀请买家获取订单分成
        $this->storeOrderCommission($order, $invite_uid, OrderCommission::TYPE_USER_INVITE);

        $invite_invite_uid = $this->user_repository->getUserInviteUid($invite_uid);
        if (!$invite_invite_uid) {
            return;
        }

        //买家邀请人是否vip
        if (!$this->isCommissionVip($invite_invite_uid)) {
            return;
        }

        //买家邀请人的vip邀请人
        $this->storeOrderCommission($order, $invite_invite_uid, OrderCommission::TYPE_USER_VIP_INVITE);
    }

    /**
     * 卖家邀请佣金提成
     *
     * @param ItemOrder $order
     */
    private function publisherInviteCommissionInit(ItemOrder $order)
    {
        $publisher_uid = $order->publisher_uid;
        $invite_uid = $this->publisher_repository->getPublisherInviteUid($publisher_uid);
        if (!$invite_uid) {
            return;
        }

        //邀请卖家获取订单分成
        $this->storeOrderCommission($order, $invite_uid, OrderCommission::TYPE_PUBLISHER_INVITE);

        $invite_invite_uid = $this->publisher_repository->getPublisherInviteUid($invite_uid);
        if (!$invite_invite_uid) {
            return;
        }

        if (!$this->isCommissionVip($invite_invite_uid)) {
            return;
        }

        //卖家邀请人的vip邀请人
        $this->storeOrderCommission($order, $invite_invite_uid, OrderCommission::TYPE_PUBLISHER_VIP_INVITE);
    }

    /**
     * 完成订单佣金分成初始化
     *
     * @param $order_id
     *
     * @return bool
     */
    private function completeCommissionInit($order_id)
    {
        $order = ItemOrder::query()->find($order_id);
        if (!$order) {
            return false;
        }

        $order->is_commission_init = 1;

        return $order->save();
    }

    /**
     * 是否订单佣金已初始化
     *
     * @param $order
     *
     * @return bool
     */
    private function isOrderCommissionInit($order)
    {
        if ($order->is_commission_init == 1) {
            return true;
        }

        if (OrderCommission::query()->where('order_id', $order->id)->count() > 0) {
            return true;
        }

        return false;
    }

    /**
     * 增加订单佣金分成记录
     *
     * @param $order_id
     * @param $user_id
     * @param $money
     * @param $type
     *
     * @return bool
     */
    private function storeOrderCommission($order, $user_id, $type)
    {
        $model = new OrderCommission();
        $model->order_id = $order->id;
        $model->user_id = $user_id;
        $model->type = $type;
        $model->status = OrderCommission::STATUS_PENDING;

        $commission_rates = [
            OrderCommission::TYPE_USER_INVITE          => env('ORDER_USER_INVITE_COMMISSION_RATE'),
            OrderCommission::TYPE_PUBLISHER_INVITE     => env('ORDER_PUBLISHER_INVITE_COMMISSION_RATE'),
            OrderCommission::TYPE_USER_VIP_INVITE      => env('ORDER_USER_VIP_INVITE_COMMISSION_RATE'),
            OrderCommission::TYPE_PUBLISHER_VIP_INVITE => env('ORDER_PUBLISHER_VIP_INVITE_COMMISSION_RATE'),
        ];

        $rate = (int)$commission_rates[$type];
        $money = sprintf('%.2f', $order->money * $rate / 100);
        $model->money = $money;

        return $model->save();
    }

    /**
     * 是否渠道推广商
     *
     * @param $user_id
     *
     * @return bool
     */
    private function isCommissionVip($user_id)
    {
        $user = $this->user_repository->show((int)$user_id);

        return $user && $user->is_commission_vip == 1;
    }
}
